<template>
  <div v-if="isPipeBrustShow" class="componentContainer" v-drag>
    <el-dialog
      title="连通性分析"
      style="width: 50%"
      :modal="false"
      :visible.sync="isPipeBrustShow"
      :close-on-click-modal="false"
      :before-close="handleClose"
    >
      <template #title>
        <div
          class="custom-header drag-handle"
          style="font-size: 1rem; display: flex"
        >
          <div
            class="bar"
            style="
              width: 5px;
              height: 20px;
              background-color: white;
              margin-right: 10px;
            "
          ></div>
          <span>连通性分析</span>
        </div>
      </template>

      <div
        style="
          margin-top: -20px;
          display: flex;
          flex-direction: column;
          justify-content: space-around;
          height: 250px;
        "
      >
        <!-- <div>
                    <span style="color: #fff; font-size: 16px;">选择分析点：</span>
                    <el-button type="primary" plain>选择</el-button>
                </div> -->
        <div>
          <span style="color: #fff; font-size: 16px">分析点1：&nbsp;</span>
          <el-input
            style="width: 50%"
            v-model="coordinateGroup.startPoint"
            placeholder="请输入坐标点(x,y)"
            @change="choosePoint('start', 'change')"
          ></el-input>
          <el-button
            type="primary"
            plain
            style="margin-left: 1.5rem"
            @click="choosePoint('start', 'button')"
            >选择</el-button
          >
        </div>
        <div>
          <span style="color: #fff; font-size: 16px">分析点2：&nbsp;</span>
          <el-input
            style="width: 50%"
            v-model="coordinateGroup.endPoint"
            placeholder="请输入坐标点(x,y)"
            @change="choosePoint('end', 'change')"
          ></el-input>
          <el-button
            type="primary"
            plain
            style="margin-left: 1.5rem"
            @click="choosePoint('end', 'button')"
            >选择</el-button
          >
        </div>
        <div class="btnGroup">
          <el-button type="primary" plain @click="connectivityAnalysis"
            >分析</el-button
          >
          <el-button @click="reset">重置</el-button>
        </div>
        <!-- <div>
                    <div
                        style="
                            width: 440px;
                            height: 30px;
                            background-color: #4070a2;
                            font-size: 16px;
                            color: white;
                            line-height: 30px;
                        "
                    >
                        连通列表输出
                    </div>
                </div> -->
      </div>
      <!-- <div>
                <el-table
                    :data="connectivityTableData"
                    border
                    style="width: 100%">
                    <el-table-column
                    prop="date"
                    label="类别">
                    </el-table-column>
                    <el-table-column
                    prop="name"
                    label="数量">
                    </el-table-column>
                </el-table> 
            </div> -->
    </el-dialog>
  </div>
</template>

<script>
import dmgis from "@/api/dmgis";
export default {
  components: {},
  data() {
    return {
      connectivityTableData: [],
      pointLayer: null,
      lineLayer: null,
      map: null,
      isPipeBrustShow: this.dialogVisible, // 初始化为从父组件传来的值
      coordinateGroup: {
        startPoint: "",
        endPoint: "",
      },
      addPointLyaer: null,
      dmPipProjectLayer: null,
    };
  },
  mounted() {
    this.map = this.$store.getters.Map;
    this.pointLayer = this.map.layer.createVectorLayer(
      "connectivityPointLayer"
    );
    this.dmPipProjectLayer = this.$store.getters.pipProjectLayer;
    this.lineLayer = this.map.layer.createVectorLayer("连通性图层", {}, 2);
  },
  destroyed() {
    if (this.map) {
      this.map.map.removeLayer(this.pointLayer);
      this.map.map.removeLayer(this.lineLayer);
    }
  },
  props: {
    dialogVisible: {
      type: Boolean,
      required: true,
    },
  },
  methods: {
    connectivityAnalysis() {
      this.lineLayer.getSource().clear();
      let prjParmas = this.dmPipProjectLayer.GetPathMapService(
        "pipeLineNet",
        "Net"
      );
      prjParmas.ex = "0";
      prjParmas.ipos = this.coordinateGroup.startPoint.replace(/,/g, " ");
      prjParmas.epos = this.coordinateGroup.endPoint.replace(/,/g, " ");
      this.dmPipProjectLayer.SendPathMapService(prjParmas).then((res) => {
        //加线
        let lineDataGroup = [];
        if (!res.strPos) {
          this.$message.error("无连通路径");
          return;
        }

        let lineData = res.strPos.split(",");
        lineData.forEach((pair) => {
          const [x, y] = pair.trim().split(" ");
          lineDataGroup.push([parseFloat(x), parseFloat(y)]);
        });
        //找最近的点
        console.log(this.coordinateGroup);

        let startPoint = this.findCloestPoint(
          this.coordinateGroup.startPoint.split(","),
          lineDataGroup
        );
        let endPoint = this.findCloestPoint(
          this.coordinateGroup.endPoint.split(","),
          lineDataGroup
        );
        console.log(startPoint, endPoint);
        this.map.marker.addLineString(
          startPoint,
          this.coordinateGroup.startPoint.split(","),
          this.lineLayer,
          {
            color: "green",
            width: 6,
          },
          "",
          ""
        );
        this.map.marker.addLineString(
          endPoint,
          this.coordinateGroup.endPoint.split(","),
          this.lineLayer,
          {
            color: "green",
            width: 6,
          },
          "",
          ""
        );
        lineDataGroup.forEach((item, index) => {
          if (index > 0) {
            this.map.marker.addLineString(
              lineDataGroup[index - 1],
              item,
              this.lineLayer,
              {
                color: "green",
                width: 6,
              },
              "",
              ""
            );
          }
        });
      });
    },
    findCloestPoint(point, pointList) {
      let closestPointDistance = 0;
      let closestPoint = [];
      pointList.forEach((item, index) => {
        if (index == 0) {
          closestPointDistance = this.findPointDistance(item, point);
          closestPoint = item;
        } else {
          let temp = this.findPointDistance(item, point);
          if (temp < closestPointDistance) {
            closestPointDistance = temp;
            closestPoint = item;
          }
        }
      });
      return closestPoint;
    },
    findPointDistance(point1, point2) {
      let dx = point2[0] - point1[0];
      let dy = point2[1] - point1[1];
      return Math.sqrt(dx * dx + dy * dy);
    },
    handleClose() {
      let mapcontanier = document.querySelector(".ol-viewport");
      mapcontanier.style.cursor = "auto";
      if (this.addPointLyaer) {
        this.map.map.un("singleclick", this.addPointLyaer);
      }
      this.map.map.removeLayer(this.pointLayer);
      this.map.map.removeLayer(this.lineLayer);
      this.isPipeBrustShow = false;
    },
    choosePoint(type, way) {
      if (way == "button") {
        if (this.addPointLyaer) {
          this.map.map.un("singleclick", this.addPointLyaer);
        }
        let mapcontanier = document.querySelector(".ol-viewport");
        mapcontanier.style.cursor = "crosshair";
        this.addPointLyaer = (event) => {
          let coordinate = event.coordinate.map((item) => {
            return item.toFixed(2);
          });
          let coordinateClick = coordinate.join(",");
          this.coordinateGroup[`${type}Point`] = coordinateClick;
          if (this.pointLayer) {
            this.pointLayer
              .getSource()
              .getFeatures()
              .forEach((feature) => {
                if (feature.type == type) {
                  this.pointLayer.getSource().removeFeature(feature);
                }
              });
            this.map.marker.addMarker(
              coordinate[0],
              coordinate[1],
              this.pointLayer,
              {
                text: {
                  font: "normal 13px 微软雅黑",
                  name: type == "start" ? "分析点1" : "分析点2",
                  fillColor: "#fff",
                  strokeColor: "#000",
                  strokeWidth: 2,
                  offsetY: 0,
                },
                scale: 1.5, //大小
                radius: 13,
                pBorderColor: "#000000",
                pBorderWidth: 1,
                pFillColor: type == "start" ? "green" : "red",
              },
              "",
              type
            );
          }
        };
        this.map.map.on("singleclick", this.addPointLyaer);
      } else {
        let coordinate = this.coordinateGroup[`${type}Point`].split(",");
        if (coordinate.length > 1 && this.pointLayer) {
          this.pointLayer
            .getSource()
            .getFeatures()
            .forEach((feature) => {
              if (feature.type == type) {
                this.pointLayer.getSource().removeFeature(feature);
              }
            });
          this.map.marker.addMarker(
            coordinate[0],
            coordinate[1],
            this.pointLayer,
            {
              text: {
                font: "normal 13px 微软雅黑",
                name: type == "start" ? "分析点1" : "分析点2",
                fillColor: "#fff",
                strokeColor: "#000",
                strokeWidth: 2,
                offsetY: 0,
              },
              scale: 1.5, //大小
              radius: 13,
              pBorderColor: "#000000",
              pBorderWidth: 1,
              pFillColor: type == "start" ? "green" : "red",
            },
            "",
            type
          );
        }
      }
    },
    reset() {
      let mapcontanier = document.querySelector(".ol-viewport");
      mapcontanier.style.cursor = "auto";
      this.pointLayer.getSource().clear();
      this.lineLayer.getSource().clear();
      this.coordinateGroup = {
        startPoint: [],
        endPoint: [],
      };
      if (this.addPointLyaer) {
        this.map.map.un("singleclick", this.addPointLyaer);
      }
    },
  },
  watch: {
    // 当父组件的 dialogVisible 变化时，更新 isPipeBrustShow
    dialogVisible(newVal) {
      this.isPipeBrustShow = newVal;
    },
  },
};
</script>

<style lang="scss" scoped>
.componentContainer {
  position: absolute;
  width: 50rem;
  height: 50rem;
  top: 0;
  left: -8vw;
  pointer-events: none;
}
::v-deep .el-dialog__wrapper {
  position: absolute !important;
  width: 60rem !important;
  pointer-events: none !important;
}
::v-deep .el-dialog {
  .el-dialog__header {
    pointer-events: auto;
  }
  .el-dialog__body {
    pointer-events: auto;
  }
  background-color: #285383;
  margin: 0;
  // margin-top: 2vh !important;
  .el-dialog__title {
    color: white;
  }
}
</style>
